<!DOCTYPE html>

<video id="video" width="100%" controls autoplay></video>
<center>
  <input id="pass" placeholder="password">
  Record <button class="record">Camera</button> or <button class="record">Screen</button>
</center>

<script src="../jquery.js"></script>
<script src="../../../gun/gun.js"></script>
<script src="../../../gun/sea.js"></script>

<script>
var gun = Gun(location.origin + '/gun');

gun.get('test').get('video').on(async function(data){
  if($('#pass').val()){ data = await SEA.decrypt(data, $('#pass').val()) }
  $('#video').get(0).src = data;
})

$('.record').on('click', function(){
  if(record.ing){
    if(record.ing.stop){ record.ing.stop() }
    $(this).text(record.type);
    record.ing = false;
    return;
  }
  record(record.type = $(this).text());
  $(this).text("End");
})

function record(type){
  if('Camera' === type){
    navigator.getMedia({ video: true, audio: true }, load, error);
  }
  if('Screen' === type){
    navigator.mediaDevices.getDisplayMedia({ video: true, audio: true }).then(load, error);
  }
  function load(media){
    var chunks = [];
    record.ing = new MediaRecorder(media);
    record.ing.ondataavailable = function(eve){ chunks.push(eve.data) }
    record.ing.onstop = function(eve){record.save(new Blob(chunks)) }
    record.ing.start();
  }
  function error(err){ console.log(err) }
}

record.save = function(data){
  record.file = record.file || new FileReader();
  record.file.readAsDataURL(data); 
  record.file.onloadend = async function(){
    var b64 = record.file.result, pass;
    b64 = $('#video').get(0).src = "data:video/webm" + b64.slice(b64.indexOf(';'));
    if($('#pass').val()){ b64 = await SEA.encrypt(b64, $('#pass').val()) }
    gun.get('test').get('video').put(b64);
  }
}

navigator.getMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia
  || navigator.mozGetUserMedia || navigator.msGetUserMedia);
</script>